﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Lenovo.CFI.BLL;
using Lenovo.CFI.Common.Dic;
using Lenovo.CFI.WebControls;
using Lenovo.CFI.Web.Helper;
using Lenovo.CFI.Common;
using Lenovo.CFI.BLL.Sys;
using TB.Web.UI.WebControls;

namespace Lenovo.CFI.Web.VP
{
    public partial class TopicSchedule : System.Web.UI.UserControl
    {
        TopicBl topicBl = new TopicBl();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                int? id = UrlHelper.GetQueryStringID();
                Topic topic = null;
                if (id.HasValue)
                {
                    topic = topicBl.GetTopicByID(id.Value);
                }
                if (topic == null) ErrorHelper.RaiseNoValueError();

                ViewState["topicid"] = topic.ID;


                if (topic.Status != TopicStatus.Schedule) ErrorHelper.RaiseError("The schedule has been setted!");


                this.DpReviewDate.Value = topic.ReviewTime.Value.ToString("yyyy-MM-dd");

                this.BindData();

                MessageHelper.Prepare(this.Page);
            }
        }


        Dictionary<int, Idea> ideasDic = null;
        List<ScheduleDetail> scheduleDetails = null;
        private void BindData()
        {
            int topicID = Convert.ToInt32(ViewState["topicid"]);
            ScheduleBl scheduleBl = new ScheduleBl();
            this.scheduleDetails = scheduleBl.GetScheduleWithTimeTable(topicID);
            if (this.scheduleDetails.Count > 0)
            {
                //this.FsSet.Visible = false;
                this.UpList.Visible = true;

                ideasDic = new Dictionary<int, Idea>();
                foreach (Idea idea in new IdeaBl().GetIdeaByScheduleTopic(topicID))
                    ideasDic.Add(idea.ID, idea);

                this.scheduleDetails.RemoveAt(0);        // 去掉开始

                this.GvList.DataSource = this.scheduleDetails;
                this.GvList.DataBind();
            }
            else
            {
                this.FsSet.Visible = true;
                this.UpList.Visible = false;
            }
        }

        protected void BtnGenerate_Click(object sender, EventArgs e)
        {
            if (!this.DpReviewDate.Date.HasValue)
            {
                MessageHelper.Show("Please select review date", this.Page);
                return;
            }

            int topicID = Convert.ToInt32(ViewState["topicid"]);

            string date = this.DpReviewDate.Date.Value.ToString("yyyy-MM-dd");
            DateTime reviewTimeAM = DateTime.Parse(date + " " + this.TxtTimeAm.Text.Trim() + ":00");
            DateTime reviewTimePM = DateTime.Parse(date + " " + this.TxtTimePm.Text.Trim() + ":00");

            try
            {
                new ScheduleBl().GenerateDefaultSchedule(topicID, reviewTimeAM, reviewTimePM);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.Show(ex.Message, this.Page);
            }

            this.BindData();
        }


        
        protected void GvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);

                ScheduleDetail scheduleDetail = (ScheduleDetail)e.Row.DataItem;

                ImageButton btnUp = (ImageButton)(e.Row.FindControl("BtnUp"));
                ImageButton btnDown = (ImageButton)(e.Row.FindControl("BtnDown"));
                ImageButton btnBreak = (ImageButton)(e.Row.FindControl("BtnBreak"));
                ConfirmImageButton btnDel = (ConfirmImageButton)(e.Row.FindControl("BtnDel"));


                ((Literal)e.Row.FindControl("LtrStart")).Text = scheduleDetail.StartTime.ToString("HH:mm");

                if (scheduleDetail.EventType == ScheduleEventType.Idea)
                {
                    Idea idea = ideasDic[scheduleDetail.IdeaID.Value];
                    ((Literal)e.Row.FindControl("LtrIdea")).Text = idea.Title;
                    ((Literal)e.Row.FindControl("LtrOwner")).Text = idea.Owner;

                    btnBreak.CommandArgument = (scheduleDetail.Sort + 1).ToString();
                }
                else if (scheduleDetail.EventType == ScheduleEventType.Break)
                {
                    ((Literal)e.Row.FindControl("LtrIdea")).Text = "Break";

                    btnBreak.Enabled = false;

                    ((TextBox)e.Row.FindControl("TxtPeriod")).ReadOnly = true;
                }

                btnUp.Visible = false;
                btnDown.Visible = false;
            }
        }

        protected void GvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "InsertBreak") //插入休息
            {
                ViewState["BreakSort"] = e.CommandArgument;

                this.MpeAddBreak.Show();
            }
            else if (e.CommandName == "Remove")
            {
                try
                {
                    new ScheduleBl().Remove(Convert.ToInt32(e.CommandArgument));

                    MessageHelper.RegShowJSAjax(this.GvList, "Success!", this.Page);
                }
                catch (ApplicationException ex)
                {
                    MessageHelper.RegShowJSAjax(this.GvList, ex.Message, this.Page);
                }

                this.BindData();
            }
        }



        protected void BtnAdd_Click(object sender, EventArgs e)
        {
            int topicID = Convert.ToInt32(ViewState["topicid"]);
            List<Idea> ideas = new IdeaBl().GetIdeaByScheduleTopicForAdd(topicID);

            if (ideas.Count == 0)
            {
                MessageHelper.RegShowJSAjax(this.BtnAdd, "No candidate ideas!", this.Page);
                return;
            }

            this.DdlIdeaAdd.DataSource = ideas;
            this.DdlIdeaAdd.DataTextField = "Title";
            this.DdlIdeaAdd.DataValueField = "ID";
            this.DdlIdeaAdd.DataBind();

            this.TxtPeriodAdd.Text = "0";
            this.TxtSortAdd.Text = "";

            this.MpeAddIdea.Show();
        }

        protected void BtnSaveAddIdea_Click(object sender, EventArgs e)
        {
            int topicID = Convert.ToInt32(ViewState["topicid"]);

            if (String.IsNullOrEmpty(this.TxtPeriodAdd.Text) || String.IsNullOrEmpty(this.TxtSortAdd.Text))
            {
                MessageHelper.RegShowJSAjax(this.BtnSaveAddIdea, "Please input period and sort!", this.Page);
                return;
            }

            int ideaID = Convert.ToInt32(this.DdlIdeaAdd.SelectedValue);
            int period = Convert.ToInt32(this.TxtPeriodAdd.Text);
            int sort = Convert.ToInt32(this.TxtSortAdd.Text);

            try
            {
                new ScheduleBl().ReviewIdea(topicID, ideaID, period, sort);

                MessageHelper.RegShowJSAjax(this.BtnSaveAddIdea, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnSaveAddIdea, ex.Message, this.Page);
            }

            this.BindData();
        }

        protected void BtnSaveAddBreak_Click(object sender, EventArgs e)
        {
            int sort = Convert.ToInt32(ViewState["BreakSort"]);
            int topicID = Convert.ToInt32(ViewState["topicid"]);

            Topic topic = new TopicBl().GetTopicByID(topicID);

            ScheduleDetail scheduleDetail = new ScheduleDetail(topicID, ScheduleEventType.Break);
            scheduleDetail.Sort = sort;

            DateTime? until = null;
            int period = 0;
            if (!String.IsNullOrEmpty(this.TxtUntil.Text))
                until = DateTime.Parse(topic.ReviewTime.Value.ToString("yyyy-MM-dd") + " " + this.TxtUntil.Text.Trim() + ":00");
            
            if (!String.IsNullOrEmpty(this.TxtPeriod.Text))
                period = Convert.ToInt32(this.TxtPeriod.Text.Trim());

            try
            {
                new ScheduleBl().InsertBreak(topicID, period, until, sort);

                MessageHelper.RegShowJSAjax(this.BtnSaveAddBreak, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnSaveAddBreak, ex.Message, this.Page);
            }

            this.BindData();
        }

        protected void BtnSaveAll_Click(object sender, EventArgs e)
        {
            int topicID = Convert.ToInt32(ViewState["topicid"]);

            List<ScheduleDetail> scheduleDetails = new List<ScheduleDetail>();
            foreach (GridViewRow row in this.GvList.Rows)
            {
                TextBox txtPeriod = (TextBox)row.FindControl("TxtPeriod");
                TextBox txtSort = (TextBox)row.FindControl("TxtSort");

                int id = Convert.ToInt32(this.GvList.DataKeys[row.RowIndex].Value);
                ScheduleEventType type = (ScheduleEventType)Convert.ToInt32(this.GvList.DataKeys[row.RowIndex].Values[1]);

                ScheduleDetail scheduleDetail = new ScheduleDetail(id);

                scheduleDetail.Sort = Convert.ToInt32(txtSort.Text);
                if (type == ScheduleEventType.Idea)
                {
                    scheduleDetail.Period = Convert.ToInt32(txtPeriod.Text);
                }

                scheduleDetails.Add(scheduleDetail);
            }


            try
            {
                new ScheduleBl().UpdateSchedules(topicID, scheduleDetails);

                MessageHelper.RegShowJSAjax(this.BtnSaveAll, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnSaveAll, ex.Message, this.Page);
            }

            this.BindData();
        }

        protected void BtnFinish_Click(object sender, EventArgs e)
        {
            int topicID = Convert.ToInt32(ViewState["topicid"]);

            try
            {
                new TopicBl().FinishSchedule(topicID);

                MessageHelper.RegShowJSAjax(this.BtnFinish, "Success!", this.Page);

                System.Web.UI.ScriptManager.RegisterStartupScript(this.BtnFinish, this.Page.GetType(), "Close",
                    String.Format(@"setTimeout(""window.location='{0}';"", 1000);", UrlHelper.GenerateUrl("topiclist")), true);

            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnFinish, ex.Message, this.Page);
            }
        }
    }
}